package cn.edu.swust.adressbook.activity;

import android.app.ActionBar;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.edu.swust.adressbook.R;
import cn.edu.swust.adressbook.adapter.GroupSelectItemAdapter;
import cn.edu.swust.adressbook.bean.Contact;
import cn.edu.swust.adressbook.bean.Group;
import cn.edu.swust.adressbook.service.IBaseService;
import cn.edu.swust.adressbook.service.impl.ContactServiceImpl;
import cn.edu.swust.adressbook.service.impl.GroupServiceImpl;


/**
 * @file 添加联系人类
 * 完成新建联系人信息保存
 */
public class AddActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private TextView mCancelButton;            ///< 取消按钮
    private TextView mFinishButton;           ///< 完成按钮
    private IBaseService mContactService;     ///< 数据库操作服务：添加，删除等
    private Contact mContact;                ///< 联系人信息
    private PopupWindow mPopWindow;          ///< 选择群组的浮框
    private Long mGroupId = null;            ///< 选择的群组ID
    private TextView mGroupSelect;           ///< 群组选择按钮
    private ListView mGroupSelectList;       ///< 群组选择列表
    private List<Group> mGroups;             ///< 群组列表
    private GroupSelectItemAdapter mGroupSelectItemAdapter; ///< 群组列表适配器

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_people);
        mContact = new Contact();
        mContactService = new ContactServiceImpl(this);
        initData();
        findView();
        setButtonListener();
    }

    /**
     * 初始化属性 mGroupSelectItemAdapter mGroups
     */
    private void initData() {
        IBaseService baseService = new GroupServiceImpl(this);
        mGroupSelectItemAdapter = new GroupSelectItemAdapter(this);
        mGroups = baseService.getAll();
        mGroupSelectItemAdapter.setGroups(mGroups);
    }

    /**
     * 判断是否为合法电话号码
     * @param phoneNumber 电话号码字符串
     * @return 若为合法电话号码则返回true，否则返回false
     */
    public static boolean isValidPhoneNumber(String phoneNumber){
        if (phoneNumber.length() == 3 || phoneNumber.length() == 6 || phoneNumber.length() == 11 ||phoneNumber.length() == 8 ){
            Pattern p = Pattern.compile("^[0-9]*$");//正则表达式判断是否为合法电话号码
//            ^[0-9]*$ ^((13[0-9])|(15[^4,\D])|(18[0-9]))\d{8}$
            Matcher m = p.matcher(phoneNumber);
            // return 结果为true or  false
            return m.matches();
        }
        return false;
    }

    /**
     * 判断联系人号码是否合法并保存合法添加联系人的信息
     */
    private void saveData(){
        String name = ((EditText) findViewById(R.id.input_people_name)).getText().toString();
        String company = ((EditText) findViewById(R.id.input_company)).getText().toString();//获取页面输入
        mContact.setCompany(company);//存至结构体
        String notes = ((EditText) findViewById(R.id.input_note)).getText().toString();
        mContact.setNotes(notes);
        String phone = ((EditText) findViewById(R.id.input_phone_num)).getText().toString();

        mContact.setGroupId(mGroupId);
       // String groupId = ((EditText) findViewById(R.id.input_group)).getText().toString();分组待完善
        //判断号码是否合法，合法就存入，否则提示错误
        if (isValidPhoneNumber(phone)){
            // 判断是否填入姓名
            if ("".equals(name)){
                //姓称即号码
                name = phone;
            }
            mContact.setName(name);
            mContact.setPhoneNumber(phone);
            mContactService.add(mContact);//保存信息
            Toast.makeText(this,"新建联系人成功！",Toast.LENGTH_LONG).show();
            finish();
        }else{
            Toast.makeText(this,"电话号码错误！",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 寻找控件，即取消按钮和完成按钮
     */
    private void findView(){
        mCancelButton = (TextView) findViewById(R.id.cancle_btn);
        mFinishButton = (TextView) findViewById(R.id.finish_btn);
        mGroupSelect = (TextView) findViewById(R.id.input_group);
    }

    /**
     * 建立监听事件
     */
    private void setButtonListener() {
        mCancelButton.setOnClickListener(this);
        mFinishButton.setOnClickListener(this);
        mGroupSelect.setOnClickListener(this);
        //findViewById(R.id.edit_button).setOnClickListener(this);
    }

    /**
     * 点击事件判断
     * @param view 要监听的控件
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.cancle_btn://取消按钮
                //跳转到主页面
                finish();
                break;
            case R.id.finish_btn://完成按钮
                //TODO: to edit many list item
                //保存数据到数据库
                saveData();
                break;
            case R.id.input_group:
                showPopupWindow();
                break;
            default:
                break;
        }
    }

    /**
     * 选择群组的浮框
     */
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(AddActivity.this).inflate(R.layout.activity_select_group_popupwindow, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOutsideTouchable(true);
        //设置各个控件的点击响应
        mGroupSelectList = (ListView) contentView.findViewById(R.id.group_pop_list);
        mGroupSelectList.setAdapter(mGroupSelectItemAdapter);
        mGroupSelectList.setOnItemClickListener(this);

        //显示PopupWindow
        View rootView = LayoutInflater.from(AddActivity.this).inflate(R.layout.activity_group_list, null);
        mPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);

    }

    /**
     * 选择群组的浮框选择的列表
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        mGroupId = mGroups.get(i).getId();
        mGroupSelect.setText(mGroups.get(i).getName());
        mPopWindow.dismiss();
    }

}
